package nacos

import (
	"gitee.com/hxchjm/log"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v2"
	"strings"
)

type NacosConfig struct {
	Addr string
	Port int
}

type NacosClient struct {
	Client config_client.IConfigClient
}

//var nacosAddr = "console.nacos.io"
var nacosAddr = "118.195.198.233"

func New() *NacosClient {
	var err error
	sc := []constant.ServerConfig{
		{
			IpAddr: nacosAddr,
			Port:   8848,
		},
	}
	//or a more graceful way to create ServerConfig
	_ = []constant.ServerConfig{
		*constant.NewServerConfig(
			"console.nacos.io",
			80,
			constant.WithScheme("http"),
			constant.WithContextPath("/nacos")),
	}

	_ = constant.ClientConfig{
		NamespaceId:         "public", //namespace id
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		RotateTime:          "1h",
		MaxAge:              3,
		LogLevel:            "debug",
	}
	//or a more graceful way to create ClientConfig
	_ = *constant.NewClientConfig(
		constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"),
		constant.WithTimeoutMs(5000),
		constant.WithNotLoadCacheAtStart(true),
		constant.WithLogDir("/tmp/nacos/log"),
		constant.WithCacheDir("/tmp/nacos/cache"),
		constant.WithRotateTime("1h"),
		constant.WithMaxAge(3),
		constant.WithLogLevel("debug"),
	)

	// a more graceful way to create config client
	client, err := clients.NewConfigClient(
		vo.NacosClientParam{
			//ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)

	if err != nil {
		panic(err)
	}
	return &NacosClient{Client: client}
}

func (nc NacosClient) Load(c interface{}) {
	content, err := nc.Client.GetConfig(vo.ConfigParam{
		DataId: "sd",
		Group:  "DEFAULT_GROUP",
	})

	if err != nil {
		log.Error("get config err(%+v)", err)
		return
	}
	log.Info("GetConfig,config:[%+v]", content)


}

func parse(){
	if err := unmarshalToml(data, config, errorOnUnmatchedKeys); err == nil {
		return nil
	} else if errUnmatchedKeys, ok := err.(*UnmatchedTomlKeysError); ok {
		return errUnmatchedKeys
	}

	if err := unmarshalJSON(data, config, errorOnUnmatchedKeys); err == nil {
		return nil
	} else if strings.Contains(err.Error(), "json: unknown field") {
		return err
	}

	var yamlError error
	if errorOnUnmatchedKeys {
		yamlError = yaml.UnmarshalStrict(data, config)
	} else {
		yamlError = yaml.Unmarshal(data, config)
	}

	if yamlError == nil {
		return nil
	} else if yErr, ok := yamlError.(*yaml.TypeError); ok {
		return yErr
	}
}